//
//  BeingLiftedView.m
//  Toyohu
//
//  Created by GuoPeng on 16/4/28.
//  Copyright © 2016年 celia. All rights reserved.
//

#import "BeingLiftedView.h"
#import "FlatButton.h"
#import "UIView+Fillet.h"
#import "ReBindView.h"

#import <ReactiveCocoa.h>
#import "NSObject+PhoneNumber.h"

#import <Masonry/Masonry.h>
#import "GPCustomMD.h"
#import "GPAFNetworking3.h"
#import "LoginManager.h"
#import "TYH_LoginLoginModel.h"

typedef void (^SuccessBlock)(NSString *str);

@interface BeingLiftedView ()
{
    NSInteger _time;
}


@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property (weak, nonatomic) IBOutlet UITextField *verificationCodeTextField;
@property (weak, nonatomic) IBOutlet UIButton *getVerificationCodeButton;
@property (weak, nonatomic) IBOutlet FlatButton *giveUpButton;
@property (weak, nonatomic) IBOutlet FlatButton *determineButton;

@property (nonatomic, copy) SuccessBlock successBlock;
@property (weak, nonatomic) IBOutlet UIView *bgView;


@property (nonatomic, strong) NSTimer *timer;


@end


@implementation BeingLiftedView

- (void)dealloc
{
    
}

- (void)signOut{
    [self.timer invalidate];
    self.timer = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setKeyboard
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewHigher:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewLower:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewHigher:(NSNotification*)note{
//    CGRect frame = [[[[UIApplication sharedApplication] delegate] window] frame];
//    if (frame.size.height == 480 && !_viewIsHigher) {
//        [UIView animateWithDuration:0.4 animations:^{
//            CGRect viewFrame = [self frame];
//            viewFrame.origin.y = viewFrame.origin.y - 91;
//            [self setFrame:viewFrame];
//        } completion:^(BOOL finshed){
//            _viewIsHigher = YES;
//        }];
//    }
    
//    [self.bgView mas_updateConstraints:^(MASConstraintMaker *make) {
//        make.bottom.equalTo(self).offset(1);
//    }];
    
    [UIView animateWithDuration:0.4f animations:^{
        self.bgView.center= CGPointMake(self.bgView.center.x, self.center.y - 100);
        
    } completion:^(BOOL finished) {
        
    }];
}

- (void)viewLower:(NSNotification*)note
{
    
//    self.bgView.center= CGPointMake(self.bgView.center.x, self.center.y + 100);
    [UIView animateWithDuration:1.0f animations:^{
        self.bgView.center = self.center;

    } completion:^(BOOL finished) {
        
    }];
    
//    [self.bgView mas_updateConstraints:^(MASConstraintMaker *make) {
//        make.center.equalTo(self);
//    }];
}

- (IBAction)giveUpClick:(id)sender
{
    [self removeFromSuperview];
}

- (IBAction)getVCClick:(id)sender
{
//    [ReBindView show];
//    [SVProgressHUD showWithStatus:@"请稍等..." maskType:SVProgressHUDMaskTypeGradient];
    SHOW_STATUS
    [GPAFNetworking3 post:GetVerify parameters:@{@"pId":[[LoginManager shareLoginManager] getPid]} progress:nil success:^(id  _Nullable responseObject) {
        TYH_LoginLoginModel *model = [[TYH_LoginLoginModel alloc] initWithDictionary:responseObject];
        if (model.code != 1) {
            SHOW_ERROR
        }else{
            [SVProgressHUD dismiss];
            SHOW_HIDDEN
        }
    } failure:^(NSString * _Nonnull errorLD) {
        SHOW_NTERROR
    }];
}

- (IBAction)determineClick:(id)sender
{
    WS
    [GPAFNetworking3 post:CheckValidateCode parameters:@{@"pId":[[LoginManager shareLoginManager] getPid],@"validCode":self.verificationCodeTextField.text} progress:nil success:^(id  _Nullable responseObject) {
        SS
        TYH_LoginLoginModel *model = [[TYH_LoginLoginModel alloc] initWithDictionary:responseObject];
        if (model.code != 1) {
            SHOW_ERROR
        }else{
            SHOW_HIDDEN
            [strongSelf removeFromSuperview];
            strongSelf.successBlock(strongSelf.verificationCodeTextField.text);
        }
    } failure:^(NSString * _Nonnull errorLD) {
        SHOW_NTERROR
    }];
    
    
}

- (void)bindEvents
{
    
    [self setKeyboard];
    
    
//    RAC(self.determineButton,enabled) = [RACSignal combineLatest:@[self.phoneTextfield.rac_textSignal] reduce:^(NSString *phoneText){
//        if ([phoneText isPhoneNumber]) {
//            return @YES;
//        }else{
//            return @NO;
//        }
//    }];
    @weakify(self);
    [[self.getVerificationCodeButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        _time = 5;
        self.timer.fireDate = [NSDate distantPast];
//        self.phoneTextfield.enabled = NO;
//        self.verificationCode.enabled = YES;
        self.getVerificationCodeButton.enabled = NO;
    }];
    self.timer = [self getTimer];
    
    RAC(self.determineButton,enabled) = [RACSignal combineLatest:@[self.verificationCodeTextField.rac_textSignal] reduce:^(NSString *verificationCodeTex){
        return @( verificationCodeTex.length > 3);
    }];
    
//    self.timeLabel.hidden = YES;
    
}

- (NSTimer *)getTimer{
    NSTimeInterval timeInterval = 1.0 ;
    NSTimer *atimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(decreaseTime) userInfo:nil repeats:YES];
    atimer.fireDate = [NSDate distantFuture];
    return atimer;
}

- (void)decreaseTime
{
    
    _time --;
//    self.obtainButton.hidden = YES;
//    self.timeLabel.text = [NSString stringWithFormat:@"%ziS",_time];
//    self.timeLabel.hidden = NO;
    [self.getVerificationCodeButton setTitle:[NSString stringWithFormat:@"%ld",(long)_time] forState:UIControlStateNormal];
    if (!_time) {
        self.timer.fireDate = [NSDate distantFuture];
//        self.obtainButton.hidden = NO;
//        self.timeLabel.hidden = YES;
        [self.getVerificationCodeButton setTitle:[NSString stringWithFormat:@"重新获取"] forState:UIControlStateNormal];
        self.getVerificationCodeButton.enabled = YES;
    }
}


- (void)initView{
    
    self.getVerificationCodeButton.clipsToBounds = YES;
    self.getVerificationCodeButton.layer.cornerRadius = self.getVerificationCodeButton.frame.size.height / 2;
    self.getVerificationCodeButton.layer.borderColor = [UIColor orangeColor].CGColor;
    self.getVerificationCodeButton.layer.borderWidth = 1.0f;
    
    self.giveUpButton.clipsToBounds = YES;
    self.giveUpButton.layer.cornerRadius = self.giveUpButton.frame.size.height / 2;
    self.giveUpButton.layer.borderColor = [UIColor orangeColor].CGColor;
    self.giveUpButton.layer.borderWidth = 1.0f;
    
    self.determineButton.clipsToBounds = YES;
    self.determineButton.layer.cornerRadius = self.determineButton.frame.size.height / 2;
    self.determineButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.determineButton.layer.borderWidth = 1.0f;
    
    [self.bgView filletWithcornerRadius:8.0f];
    
//    loginInfo
    NSString *phoneStr = GPGET(@"user_phone");
    self.phoneLabel.text = [NSString stringWithFormat:@"%@****%@",[phoneStr substringToIndex:3],[phoneStr substringFromIndex:7]];
}

+ (void)show
{
//    WS
    
    [[[self alloc] init] initWithSuccessBlock:^(NSString *str) {
        
//        SS
        [ReBindView show:str];
//        [ReBindView show:@"jjj"];
        
    } frame:[[UIScreen mainScreen] bounds]];
}

- (instancetype)initWithSuccessBlock:(void (^)(NSString *str))successBlock frame:(CGRect)frame
{
    self = [[[NSBundle mainBundle] loadNibNamed:@"BeingLiftedView" owner:self options:nil] objectAtIndex:0];
    if (self) {
        self.frame = frame;
        [self bindEvents];
        [self initView];
        
        _successBlock = successBlock;
        
        [[[UIApplication sharedApplication] keyWindow] addSubview:self];
        
    }
    return self;
    
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
